# -*- coding: utf-8 -*-
# Data structure
#   map[name] = [[PNAME, PTIME], ]
# 
# 该文件主要用于统计周报缺失的情况，并对月报进行汇总
# 可使用持久化文件
# 
import sys
from xlrd import open_workbook
import xlwt

import pickle, getopt, os
import copy

from config import *
from wtcommon import *

import time

def get_group_by_index(idx, idx_map):
    i = 0
    for sep in idx_map[0]:
        if idx < sep:
            break
        i = i+1

    # 做一个补偿
    i=i-1
    return idx_map[1][i]

def format_worktime(p1name, p1time, p2name, p2time):
    wt = []
    if (p2name == ""):
        wt = [[p1name, p1time, 100]]
    else:
        try:
            total = p1time + p2time
        except TypeError:
            #print "p1", p1name, p1time, "p2", p2time
            total = p1time
        if total < 5: total = 10
        total /= 100
        p1 = round(p1time/total)
        p2 = 100 - p1
        wt = [[p1name, p1time, p1], [p2name, p2time, p2]]
    return wt

def format_project(p1name):
    if len(p1name) == 0:
        return p1name
    else:
        return p1name.split()[-1]

def read_worktime(filename):
    ret = {}
    wb = open_workbook(filename)   
      
    for s in wb.sheets():   
        for row in range(1, s.nrows):
            dep    = s.cell(row, NDEP_INDEX  ).value
            week   = int(s.cell(row, NWEEK_INDEX ).value)
            name   = s.cell(row, NNAME_INDEX ).value
            pname  = s.cell(row, NPNAME_INDEX).value
            ptime  = s.cell(row, NPTIME_INDEX).value
            ttime  = s.cell(row, NTTIME_INDEX).value
            job    = s.cell(row, NPJOB_INDEX ).value
            #print name, p1name, p1time, p2name, p2time
            # 获取周表
            try:
                week_table = ret[week]
            except KeyError:
                ret[week] = {}
                week_table = ret[week]

            try:
                person_table = week_table[name]
            except KeyError:
                week_table[name] = []
                person_table = week_table[name]

            person_table.append([dep, week, name, pname, ptime, ttime, job])
    return ret

def print_xhh_format(name, result, l=30):
    temp = ['0']*l
    dtemp = ['0']*l
    for k, v in result.items():
        temp[k] = str(v)
        if (k>2):
            dtemp[k] = u'开发'.encode('gbk')
    print name+'\t'+'\t'.join(temp)
    print name+'\t'+'\t'.join(dtemp)

def print_matrix(src, nlist=[], plist=[]):
    if (len(plist) == 0):
        for k, v in ret.items():
            print k,
            for wt in v:
                print wt[PNAME_INDEX], wt[PPERC_INDEX],
            print
    else:
        l = len(plist)
        for name in nlist:
            try:
                worktime = src[name]
                #print name.encode('gbk'), 
                result = {}
                for wt in worktime:
                    pname = wt[PNAME_INDEX]
                    try:
                        idx = plist.index(pname)
                    except ValueError:
                        idx = 1
                    result[idx] = wt[PPERC_INDEX]/100
                    #if (pname in plist):
                    #    print 'Y'
                    #else:
                    #    print pname
                #print result
                print_xhh_format(name.encode('gbk'), result, l)
            except KeyError:
                print name.encode('gbk')+ "\tNO"
                print name.encode('gbk')+ "\tNO"

def print_week_table(wt):
    for k, v in wt.items():
        print '===', k.encode('gbk')
        for item in v:
            print '------',
            print item[NPNAME_INDEX].encode('gbk'), item[NPTIME_INDEX]

def print_all_table(w):
    weeks = sorted(w.keys())
    for week in weeks:
        print '=WEEK', week
        print_week_table(w[week])

def fill_table(wt, names, groups, fdouble=False, dstname="Full.xls"):
    """
    @param wt 
    @param names 
    @param fdouble 表示是否按照双行填充
    @dstname 目标文件
    """
    nwb = xlwt.Workbook()

    sheet = nwb.add_sheet('Formatted')
    line = set_sheet_format(sheet)

    weeks = sorted(wt.keys())
    jobsbyp = {}

    for week in weeks:
        i = -1
        for name in names:
            i = i+1
            try:
                worktime = wt[week][name]
                del wt[week][name]
            except:
                group = get_group_by_index(i, groups)
                worktime = [[group, week, name, "", 0, 0, ""]]

            if fdouble:
                if len(worktime) == 1:
                    item = copy.copy(worktime[0])
                    item[NPNAME_INDEX] = "NULL"
                    item[NPTIME_INDEX] = 0
                    worktime.append(item)
            for job in worktime:
                line = write_line(sheet, line, job)
                projectname = job[NPNAME_INDEX]
                try:
                    jobsbyp[projectname].append(job)
                except KeyError:
                    jobsbyp[projectname] = [job]

    nwb.save(dstname)
    return jobsbyp


def filter_workbook(w, pref):
    os.makedirs(pref)
    for p, r in w.items():
        if p!= "":
            np = p.replace('"', '').replace(' ', '_').replace('\n', '_')
            nwb = xlwt.Workbook()
            sheet = nwb.add_sheet('project')
            line = set_sheet_format(sheet)
            for job in r:
                line = write_line(sheet, line, job)
            nwb.save(pref+'/'+np+'.xls')

def usage():
    print u"""
%s [OPTS] <filename>
    """%os.path.split(sys.argv[0])[-1]

if __name__ == '__main__':
    command = ""
    starti = 1
    if (len(sys.argv) > 1):
        if (sys.argv[1][0] != '-'):
            command = sys.argv[1]
            starti += 1
    opts, args = getopt.getopt(
        sys.argv[starti:], "ho:", 
        [
            "help", "version", "data=", 
        ])

    if len(args) == 0 and len(opts) == 0:
        usage()
        sys.exit(2)

    datafile=""
    for o, a in opts:
        if o in ('--data'):
            datafile = a
        elif o in ('--version'):
            usage()
        else:
            pass

    if len(args) > 0:
        w = read_worktime(args[0])
        if (datafile != ""):
            pickle.dump(w, open(datafile, 'wb'))
    else:
        w = pickle.load(open(datafile, 'rb'))

    if command == "":
        # 载入数据表
        print_all_table(w)
    elif command == "fill":
        # 填充未填的人
        #tstr = str(int(time.time()))
        tstr = time.strftime("%Y%m%d%H%M%S",time.localtime())
        print u"根据姓名列表填充excel，未填写的人填空..."
        ret = fill_table(w, name_list, group_list, False, u'_软件所月报_个人填报版'+tstr+'.xls')
        print u"以下是在数据中填报，但未在姓名列表中的数据"
        print
        print_all_table(w)
        filter_workbook(ret, tstr)
    elif command == "filldouble":
        # 填充未填的人
        print u"根据姓名列表填充excel，未填写的人填空..."
        fill_table(w, name_list, group_list, True, 'DFull.xls')
        print u"以下是在数据中填报，但未在姓名列表中的数据"
        print
        print_all_table(w)
    else:
        print "unknow command"

